package com.alarm.ecp;

import com.alarm.ecp.constant.EventConstant;
import com.alarm.ecp.pojo.EventPO;
import com.alarm.ecp.utils.KafkaUtil;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.io.IOException;

/**
 * 基于【个体模式】检测最近1分钟内登录失败超过3次的用户
 * CEP模式：允许这3次登录失败事件之间出现其他行为事件（不连续）【宽松近邻】
 */
public class LoginFailBySingleton {
    public static void main(String[] args) throws IOException {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        // kafka数据源
        DataStream<EventPO> eventStream = KafkaUtil.read(args, env);

        // 生成keyedStream 用户id分组
        KeyedStream<EventPO, Integer> keyedStream = eventStream.keyBy((KeySelector<EventPO, Integer>) EventPO::getUserId);

        // 生成模式
        Pattern<EventPO, EventPO> pattern = Pattern.<EventPO>begin("login_fail_first") // pattern名称
        /**
         * 1、IterativeCondition 抽象类 表示通用的匹配规则 需要实现抽象方法 filter，需传入2个参数
         * 2、SimpleCondition 继承IterativeCondition，表示简单的匹配规则  需要实现抽象方法 filter，需传入1个参数
         */
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        // 登录失败事件
                        return EventConstant.LOGIN_FAIL.equals(eventPO.getEventName());
                    }
                }).times(3) // 3次，宽松邻近
                .within(Time.seconds(60)); // 最近一分钟
    }
}
